<?php namespace App\Services;

use League\Flysystem\Exception;
use Requests;
use Requests_Exception;

class WikeSms
{
    private $account    = 'gzbqxx';
    private $pswd     = 'GZbqxx05';
    private $baseUrl = 'http://120.24.167.205/msg/HttpSendSM';

    /**
     * @param $phone
     * @param $code
     * @return bool
     */
    public function  sendSms($phone,$code)
    {
        $result = self::doPost([
            'account'    => $this->account,
            'pswd'       => $this->pswd,
            'mobile'     => $phone,
            'msg'        => '【Wike众包】欢迎您注册WIKE众包平台，您的验证码为【'.$code.'】,请您30分钟内使用',
            'needstatus' => true,
            'product'    => ''
        ]);
        return $result;
    }

    /**
     * @param $code
     * @return array
     */
    public function vars($code)
    {
        return array(
            'code' =>$code
        );
    }

    /**
     * @param $url
     * @param array $param
     * @return mixed
     * @throws SendSmsException
     */
    public function doPost(array $param)
    {
        $response = null;
        try{
            $response = Requests::post($this->baseUrl,[
                'Accept'       => 'text/plain;charset=utf-8',
                'Content-Type' => 'application/x-www-form-urlencoded;charset=utf-8',
            ],$param);
        }catch (Requests_Exception $ex)
        {
            throw new SendWikeSmsException(SendWikeSmsException::RequestsException,['message' => $ex->getMessage()]);
        }

        if(!$response->success){
            switch($response->status_code){
                default:
                    throw new SendWikeSmsException(SendWikeSmsException::HttpException);
            }
        }

//        $res = json_decode($response->body);
//        if(is_null($res))
//            throw new SendSmsException(SendSmsException::NotJson);

        return json_encode($response);
//        if($res->status == 'error'){
//            throw new SendSmsException(SendSmsException::OutOfService,['msg' => $res->msg]);
//        }
    }
}

/**
 * Class SendSmsException
 * @package App\Services
 */
class SendWikeSmsException extends Exception
{
    const RequestsException = 0x01;
    const HttpException = 0x02;
    const OutOfService = 0x03;
    const NotJson = 0x04;

    /**
     * @param string $code
     * @param array $data
     * @param Exception $previous
     */
    public function __construct($code, array $data = [], Exception $previous = null)
    {
        switch ($code) {
            case self::RequestsException:
                $message = trans('exception.SendSms.requests_exception', []);
                break;
            case self::OutOfService:
            case self::NotJson:
                $message = trans('exception.SendSms.out_of_service', []);
                break;
            default:
                $message = trans('general.unknown_exception');
                break;
        }

        parent::__construct($message, $code, $previous);
    }
}